<?php
/**
 * 飞信机器人--会话管理
 * 功能： 核心库：实现 菜单导航、功能分发、会话管理
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/

require_once('./plugins/inc/db.inc.php');
require_once('./plugins/provider/CommonPlugin.class.php');

class CSession
{
	var $db;
	var $srvMobile;
	var $srvFetion;
	var $buddyURI;

	var $testNoArr;
	
	var $buddyID;
	var $buddyArray;
	var $sessionArr;
	var $currentMenu;
	var $depth=0;
	
	public function getBuddyName()
	{
		$name = $this->buddyArray['nick_name'];
		if( empty($name) )
		{
			$name = $this->buddyArray['local_name'];
			if( empty($name) )
			{
				$name = $this->buddyArray['mobile'];
				if( empty($name) )
				{
					$name = $this->buddyArray['sid'];
				}
			}
		}
		return $name;
	}
	public function CSession(&$srvMobile,&$srvFetion,&$buddyURI)
	{
		$this->srvMobile = &$srvMobile;
		$this->srvFetion = &$srvFetion;
		$this->buddyURI = &$buddyURI;
		$this->db = new CDb($srvMobile);;
		$this->testNoArr =  explode(",", TEST_NO);
		
		$this->buddyID = 0;
		
		$sql = "select * from fx_buddies where uri='$buddyURI'";
		$retArr = $this->db->fetchQueryAll($sql);

		if( count($retArr) == 0 )
		{
			$this->sessionArr = array();
			$this->buddyArray = array();
			return;
		}
		
		$this->buddyArray = $retArr[0];
		$this->buddyID = $this->buddyArray['id'];
		
		if( empty($this->buddyArray['session']) )
		{
			$this->sessionArr = array();
		}else
		{
			$this->sessionArr = unserialize($this->buddyArray['session']);
		}
	}

	private function save()
	{
		if( $this->buddyID == 0 )return;
		$s = serialize($this->sessionArr);
		
		$sql = "update fx_buddies set session='$s' where id={$this->buddyID}";
		$this->db->execute($sql);
	}

	public function getStr($key)
	{
		if( isset($this->sessionArr[$key]) )return $this->sessionArr[$key];
		return "";
	}
	public function getValue($key)
	{
		if( isset($this->sessionArr[$key]) )return intval($this->sessionArr[$key]);
		return 0;
	}
	public function set($key, $value)
	{
		$this->sessionArr[$key] = $value;
		$this->save();
	}
	public function toFull($i)
	{
		$arr = array("１","２","３","４","５","６","７","８","９","１０","１１","１２","１３","１４","１５","１６","１７","１８","１９","２０","２１","２２","２３","２４");
		//$ret = "【".$arr[$i-1]."】";  模式1
		$ret = $arr[$i-1].".";			//模式2
		return $ret;
	}
	public function fullPad($str, $len)
	{
		$temp = $str;
		$l = mb_strlen($str, 'utf-8');
		
		if( $len>$l)
		for($i=0; $i<$len-$l; $i++)$temp.="　";
		
		return $temp;
	}

	public function getCurrentMenu()
	{
		$currentNode = $this->getValue('NODE');
		$currentMenu = array();
		
		if( $currentNode>0 )
		{
			if( in_array($this->buddyURI, $this->testNoArr ))
			{
				$currentMenu = $this->db->fetchQueryAll('select * from fx_menus where id='.$currentNode.' order by s_order,id');
			}else
			{
				$currentMenu = $this->db->fetchQueryAll('select * from fx_menus where disabled=0 and id='.$currentNode.' order by s_order,id');
			}
			if(count($currentMenu)==1 && !empty($currentMenu[0]['plugin_name']) )
			{
				$this->currentMenu = $currentMenu[0];
				
				$pluginName = $currentMenu[0]['plugin_name'];
				require_once('./plugins/provider/'.$pluginName.'.class.php');
				$plugin = new $pluginName($this, $currentMenu[0]['p_id'],$currentMenu[0]['extra_param']);
				$body = $plugin->getTips();
				$this->set('PLUGIN',$pluginName);
				return FetionEncodeMsg($body);
			}
		}
		
		$hasTitle = false;
		$title = "<Font Face='仿宋' Color='-8388608' Size='12'>{tips}{title}</Font>\n";
		if( $currentNode>0 && count($currentMenu)==1 )
		{
			$title = str_replace('{tips}', $currentMenu[0]['tips'], $title);
			if(  strlen($currentMenu[0]['tips'])>0 )$hasTitle = true;
		}else 
		{
			$title = str_replace('{tips}', '', $title);
		}		
		$body = "<Font Face='楷体' Color='-16744320' Size='10.5'>{body}</Font>\n";
		$foot = "<Font Face='楷体' Color='-8388608' Size='10.5'>{foot}</Font>\n";
		
		if( in_array($this->buddyURI, $this->testNoArr) )
		{
			$menuList = $this->db->fetchQueryAll('select * from fx_menus where  p_id='.$currentNode.' order by s_order,id');
		}else
		{
			$menuList = $this->db->fetchQueryAll('select * from fx_menus where  disabled=0 and  p_id='.$currentNode.' order by s_order,id');
		}
	
		$tmpBodyStr = "";
		$tmpTitleStr = "";
		$tmpFootStr = "";
		
		$key = 1;
		$menuCount = count($menuList);
		for($i=0; $i<count($menuList); $i++)
		{
			switch( $menuList[$i]['c_type'] )
			{
				case 0:$tmpTitleStr = $menuList[$i]['title']."\n";
						break;
				case 1:
						/*if( $menuCount > 10 )
						{
							$st = $this->toFull($key).$menuList[$i]['title'];
							if($key % 2 == 1 )$st = $this->fullPad($st,12);
							$tmpBodyStr .= $st;
							if($key % 2 == 0 )$tmpBodyStr .="\n";
						}else*/ 
						{
							$tmpBodyStr .= $this->toFull($key).$menuList[$i]['title']."\n";
						}
						$key++;
						break;
				case 2:$tmpFootStr = "\n".$menuList[$i]['title'];
						break;
			}
		}
		if($key % 2 == 0 ) $tmpBodyStr.="\n";
		$tmpBodyStr = substr($tmpBodyStr,0,strlen($tmpBodyStr)-1);
		$body = str_replace('{body}', $tmpBodyStr, $body);
		
		(empty($tmpTitleStr)&&!$hasTitle)?$title="":$title=str_replace('{title}',$tmpTitleStr,$title);
		empty($tmpFootStr)?$foot="":$foot=str_replace('{foot}',$tmpFootStr,$foot);
		
		if( empty($tmpFootStr) && $currentNode>0 )
		{
			//$foot = "\n【m-返回主菜单,q-返回上一级】";
			$foot = "\n<Font Face='楷体' Color='-8388608' Size='10.5'>【m-返回主菜单】</Font>";
		}
		return FetionEncodeMsg($title.$body.$foot);
	}
	
	public function handleMsg($input,$type='text/html')
	{
		$time = time(NULL);
		$buddy_uri = $this->buddyURI;
		
		// update buddy last_update_time
		$sql = "update fx_buddies set last_update_time={$time} where id={$this->buddyID}";
		$this->db->execute($sql);
		
		$inputEncode = mysql_real_escape_string($input);
		if( !( strlen($input)==1 && is_numeric($inputEncode) ) )
		{
			$sql = "insert into fx_incomming_messages(buddy_uri,message,add_time)";
			$sql.= " values('{$buddy_uri}','{$inputEncode}','{$time}')";
			$this->db->execute($sql);
		}
		
		/*每日积分*/
		$msg = '登录';
		CommonPlugin::addScore($this->db, $this->buddyID, 1, 10, $msg);
		
		// 短指令判断
		//if( $type == 'text/plain')
		{
			if ($handle = opendir('./plugins/provider/'))
			{
			    while (false !== ($file = readdir($handle)))
			    {
			        if ($file != "." && $file != "..")
			        {
			        	preg_match_all('/([0-9A-Za-z]*).class.php/',$file,$matches);
			        	if( is_array($matches) && count($matches)==2 )
			        	{
			            	if(isset($matches[1][0]) && $matches[1][0]!='CommonPlugin')
			            	{
			            		$pluginName = $matches[1][0];
			            		require_once('./plugins/provider/'.$pluginName.'.class.php');
								$plugin = new $pluginName($this, 0, '');
								if( method_exists($pluginName,'shortcut'))
								{
									$done = false;
									$body = $plugin->shortcut($input,$done);
									
									if( $done )
									{
										return FetionEncodeMsg($body);
									}
								}			
			            	}
			        	}
			        }
			    }
			    closedir($handle);
			}
		}
		//
		
		$currentNode = $this->getValue('NODE');
		// 已经在plugin空间
		if( $this->getStr('PLUGIN')!="")
		{
			$currentPlugin = $this->getStr('PLUGIN');
			
			if( in_array($this->buddyURI, $this->testNoArr ))
			{
				$currentMenu = $this->db->fetchQueryAll('select * from fx_menus where id='.$currentNode.' order by s_order,id');
			}else
			{
				$currentMenu = $this->db->fetchQueryAll('select * from fx_menus where disabled=0 and id='.$currentNode.' order by s_order,id');
			}
			
			$this->currentMenu = $currentMenu[0];
			$parentID = 0;
			$extraPara = "";
			if( count($currentMenu) == 1 )
			{
				$parentID = $currentMenu[0]['p_id'];
				$extraPara = $currentMenu[0]['extra_param'];;
			}
			require_once('./plugins/provider/'.$currentPlugin.'.class.php');
			$plugin = new $currentPlugin($this, $parentID, $extraPara);
			$body = $plugin->handle($input);			
			if($body)
			{
				return FetionEncodeMsg($body);
			}else 
			{
				return $this->getCurrentMenu();
			}
		}else
		{
			// 顶级页面的帮助和建议
			if( $currentNode == 0 && ($input=='?' || $input=='j' || $input=='J') )
			{
				$pluginName = ($input=='?')?'Help':'Advice';
				require_once('./plugins/provider/'.$pluginName.'.class.php');
				$plugin = new $pluginName($this, 0, "");
				$body = $plugin->getTips();			
				$this->set('PLUGIN',$pluginName);
				return FetionEncodeMsg($body);
			}else if ($currentNode>0 && ($input=='m' || $input=='q'))
			{
				if( $input == 'm')
				{
					$this->set('NODE',0);
					$this->set('PLUGIN','');
				}
				if( $input == 'q')
				{
					$currentMenu = $this->db->fetchQueryAll('select * from fx_menus where id='.$currentNode);
					$this->set('NODE',$currentMenu[0]['p_id']);
					$this->set('PLUGIN','');
				}
				return $this->getCurrentMenu();	
			}
		}
		
		if( in_array($this->buddyURI, $this->testNoArr) )
		{
			$menuList = $this->db->fetchQueryAll('select * from fx_menus where  p_id='.$currentNode.' order by s_order,id');
		}else
		{
			$menuList = $this->db->fetchQueryAll('select * from fx_menus where  disabled=0 and  p_id='.$currentNode.' order by s_order,id');
		}
		
		$key = 1;
		for($i=0; $i<count($menuList); $i++)
		{
			switch( $menuList[$i]['c_type'] )
			{
				case 1:
					if( $key == $input )
					{
						$this->set('NODE', $menuList[$i]['id']);
						return $this->getCurrentMenu();
					}
					$key++;
					break;
			}
		}
		return "您的输入错误！请重新输入！\n".$this->getCurrentMenu();		
	}
}
?>
